package com.tron.dobest.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class TronSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    TronLogoutHandler tronLogoutHandler;

    /**
     * 通过重载，配置Spring Security的Filter链
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    /**
     * 通过重载，配置如何通过拦截器保护请求
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/rest/**","/userLogout","/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin(from->from.loginPage("/login").permitAll().successForwardUrl("/getLoginUserInfo"))
                .logout(logout->logout.logoutUrl("/logout").addLogoutHandler(tronLogoutHandler).logoutSuccessUrl("/userLogout"))
                ;
    }

    /**
     * 认证管理器构建
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(new TronUserDetailsService())
                .passwordEncoder(new TronPasswordEncoder())
        ;
    }

}
